package com.imooc.mall.controller;

import com.github.pagehelper.PageInfo;
import com.imooc.mall.common.ApiRestResponse;
import com.imooc.mall.common.Constant;
import com.imooc.mall.exception.ImoocMallException;
import com.imooc.mall.exception.ImoocMallExceptionEnum;
import com.imooc.mall.model.request.AddProductReq;
import com.imooc.mall.model.request.UpdateProductReq;
import com.imooc.mall.service.ProductService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import javax.validation.Valid;
import java.io.File;
import java.io.IOException;
import java.net.URI;
import java.net.URISyntaxException;
import java.util.UUID;

@RestController
public class ProductAdminController {

    @Autowired
    ProductService productService;

    @PostMapping("admin/product/add")
    public ApiRestResponse addProduct(
            @Valid
            @RequestBody AddProductReq addProductReq
    ) {
        productService.add(addProductReq);
        return ApiRestResponse.success();
    }

    @PostMapping("admin/upload/file")
    public ApiRestResponse upload(
            HttpServletRequest httpServletRequest,
            @RequestParam("file") MultipartFile file
    ) {
        // 获取文件名
        String filename = file.getOriginalFilename();
        assert filename != null;
        // 文件后缀名
        String suffixName = filename.substring(filename.lastIndexOf("."));
        // 生成文件名称 uuid
        String newFileName = UUID.randomUUID().toString() + suffixName;
        // 创建文件夹
        File fileDirectory = new File(Constant.FILE_UPLOAD_DIR);
        // 目标文件
        File destFile = new File(Constant.FILE_UPLOAD_DIR + newFileName);
        // 校验文件夹是否存在
        if (!fileDirectory.exists()) {
            // 不存在目录则创建
            if (!fileDirectory.mkdir()) {
                throw new ImoocMallException(ImoocMallExceptionEnum.MAKE_DIR_FAILED);
            }
        }
        // 上传文件 把 前端传递的 file 写入到新创建的文件中
        try {
            file.transferTo(destFile);
        } catch (IOException e) {
            e.printStackTrace();
        }

        try {
            /*httpServletRequest.getRequestURL() 获取当前 URL
            uri = new URI(httpServletRequest.getRequestURL()+"");*/
            return ApiRestResponse.success(getHostPort(new URI(httpServletRequest.getRequestURL()+""))+ "/images/" + newFileName );
        } catch (URISyntaxException e) {
            throw new ImoocMallException(ImoocMallExceptionEnum.UPLOAD_FAILED);
        }
    }

    /**
     * 获取 uri
     * @param uri uri
     * @return uri
     */
    private URI getHostPort(URI uri) {
        URI effectiveURI = null;
        try {
            effectiveURI = new URI(uri.getScheme(), uri.getUserInfo(), uri.getHost(), uri.getPort(), null, null, null);
        } catch (URISyntaxException e) {
            e.printStackTrace();
        }
        return effectiveURI;
    }

    @PostMapping("admin/product/update")
    public ApiRestResponse updateProduct(
            @Valid @RequestBody UpdateProductReq updateProductReq
    ) {
        productService.update(updateProductReq);
        return ApiRestResponse.success();
    }

    @PostMapping("admin/product/delete")
    public ApiRestResponse deleteProduct(
            @RequestParam("id") Integer id
    ) {
        productService.delete(id);
        return ApiRestResponse.success();
    }

    @PostMapping("admin/batchupdate/status")
    public ApiRestResponse batchUpdateStatus(
            @RequestParam("ids") Integer[] ids,
            @RequestParam("status") Integer status
    ) {
        productService.batchUpdateStatus(ids, status);
        return ApiRestResponse.success();
    }

    @PostMapping("admin/product/list")
    public ApiRestResponse<PageInfo> selectListForAdmin(
            @RequestParam("pageNum") Integer pageNum,
            @RequestParam("pageSize") Integer pageSize
    ) {
        PageInfo list = productService.listForAdmin(pageNum, pageSize);
        return ApiRestResponse.success(list);
    }
}
